
package com.com.corejavalearnings.database;

import com.jolbox.bonecp.BoneCPDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by pankaj on 7/13/14.
 */
public class LocalDB {
    private static Map<String, LocalDB> cache = new HashMap<String, LocalDB>();

    private  ComboPooledDataSource cpds;
    private  BoneCPDataSource bCPDS;

    static Logger logger = Logger.getLogger(LocalDB.class.getName());

    static {
        logger.setParent(Logger.getLogger(LocalDB.class.getPackage().getName()));
    }

    private LocalDB(String dataSource) throws IOException, SQLException, PropertyVetoException{
        setUpC3P0ConnectionPooling(dataSource);
        setUpBoneCPConnectionPooling(dataSource);
    }

    public static synchronized LocalDB getInstance(String dataSource) throws IOException, SQLException, PropertyVetoException {
        LocalDB instance = cache.get(dataSource);
        if(instance == null){
            instance = new LocalDB(dataSource);
            cache.put(dataSource, instance);
        }
        //printCache();
        return instance;
    }

    public static void printCache(){
        for(Map.Entry<String,LocalDB> entry: cache.entrySet()){
            logger.info(entry.getKey() + "    " +entry.getValue());
        }
    }

    public void setUpC3P0ConnectionPooling(String dataSource) throws PropertyVetoException{
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("org.postgresql.Driver"); //loads the jdbc driver
        cpds.setJdbcUrl("jdbc:postgresql://localhost:5432/"+dataSource);
        cpds.setUser("postgres");
        cpds.setPassword("root");

        // the settings below are optional -- c3p0 can work with defaults
        cpds.setMinPoolSize(0);
        cpds.setMaxPoolSize(2);
        cpds.setMaxIdleTime(90);

    }

    public  void setUpBoneCPConnectionPooling(String dataSource) throws PropertyVetoException{
        bCPDS = new BoneCPDataSource();
        bCPDS.setDriverClass("org.postgresql.Driver");
        bCPDS.setJdbcUrl("jdbc:postgresql://localhost:5432/"+dataSource);
        bCPDS.setUsername("postgres");				// set the username
        bCPDS.setPassword("root");				// set the password
        //ds.setXXXX(...);				// (other config options here)

        bCPDS.setPartitionCount(1);
        bCPDS.setMinConnectionsPerPartition(0);
        bCPDS.setMaxConnectionsPerPartition(2);
        bCPDS.setMaxConnectionAgeInSeconds(90);
    }

    public Connection getC3P0Connection() throws SQLException {
        return this.cpds.getConnection();
    }

    public Connection getBoneCPConnection() throws SQLException {
        return this.bCPDS.getConnection();
    }
}




